package com.sxbbc.plat.controller.jz;

import java.math.BigDecimal;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.function.common.GetRest;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.rest.RestResponse;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.core.dto.jz.*;
import com.sxbbc.common.core.entity.jz.BMoneyDetail;
import com.sxbbc.common.core.entity.jz.CCustomer;
import com.sxbbc.common.core.entity.jz.OrderMain;
import com.sxbbc.common.core.entity.jz.SysDealData;
import com.sxbbc.common.core.enums.*;
import com.sxbbc.common.core.mapper.jz.OrderMainMapper;
import com.sxbbc.common.core.mapper.jz.SysCashDetailsMapper;
import com.sxbbc.common.core.mapper.jz.SysDealDetailMapper;
import com.sxbbc.common.core.service.*;
import com.sxbbc.common.core.service.system.mode.ModeService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.sxbbc.common.basics.rest.RestFactory;
import com.sxbbc.common.core.utils.BasePage;
import com.sxbbc.plat.common.AccountMapping;

/**
 * 财务管理 控制层
 *
 * @author Wahyee
 */
@Controller
public class AccountController {

    @Autowired
    private IBAccountService bAccountService;
    @Autowired
    private IBMoneyDetailService bMoneyDetailService;
    @Autowired
    private ISysDealDataService sysDealDataService;
    @Autowired
    private IInfoParamService infoParamService;
    @Autowired
    private ModeService modeService;
    @Autowired
    private SysDealDetailMapper sysDealDetailMapper;
    @Autowired
    private SysCashDetailsMapper sysCashDetailsMapper;
    @Autowired
    private ICCustomerService customerService;
    @Autowired
    private OrderMainMapper orderMainMapper;
    @Autowired
    private IOrderMainService orderMainService;


    /**
     * 订单退款明细-页面
     *
     * @return
     */
    @RequestMapping(value = AccountMapping.SHOW_BUSINESS_ORDER_REFUND_DETAIL)
    public ModelAndView showBusinessOrderRefundDetail(Integer bid, Integer timeDays) {
        ModelAndView view = new ModelAndView(AccountMapping.SHOW_BUSINESS_ORDER_REFUND_DETAIL);
        view.addObject("bid", bid);
        view.addObject("timeDays", timeDays);
        return view;
    }

    /**
     * 订单退款明细列表
     *
     * @return
     */
    @RequestMapping(value = AccountMapping.QUERY_BUSINESS_ORDER_REFUND_DETAIL)
    @ResponseBody
    public com.sxbbc.common.basics.rest.RestResponse queryBusinessOrderRefundDetail(BasePage<OrderMain> page, OrderMain orderMain, Integer timeDays) {
        if (timeDays == null) {
            timeDays = 30;
        }
        // 订单列表
        orderMainService.queryBusinessOrderRefundDetail(page, orderMain,timeDays);
        return RestFactory.success(page.getRecords(), page.getTotal());
    }


    /**
     * 订单退款排行-页面
     *
     * @return
     */
    @RequestMapping(value = AccountMapping.SHOW_ORDER_REFUND)
    public ModelAndView showOrderRefund(DataOrderRefundVo vo) {
        ModelAndView view = new ModelAndView(AccountMapping.SHOW_ORDER_REFUND);
        view.addObject("vo", vo);
        return view;
    }

    /**
     * 查询订单退款排行
     *
     * @param vo 查询条件
     * @return
     */
    @RequestMapping(value = AccountMapping.QUERY_ORDER_REFUND)
    @ResponseBody
    public com.sxbbc.common.basics.rest.RestResponse queryOrderRefund(DataOrderRefundVo vo) {
        if (vo.getSearchNum() == null) {
            vo.setSearchNum(10);
        }
        if (vo.getTimeDays() == null) {
            vo.setTimeDays(30);
        }
        List<DataOrderRefundVo> list = orderMainMapper.queryOrderRefund(vo);
        return RestFactory.success(list, vo.getSearchNum());
    }


    /**
     * 用户余额提现排行-页面
     *
     * @return
     */
    @RequestMapping(value = AccountMapping.SHOW_CUSTOMER_CASH)
    public ModelAndView showCustomerCash(DataCashVO vo) {
        ModelAndView view = new ModelAndView(AccountMapping.SHOW_CUSTOMER_CASH);
        view.addObject("vo", vo);
        return view;
    }


    /**
     * 查询用户余额提现排行
     *
     * @param vo 查询条件
     * @return
     */
    @RequestMapping(value = AccountMapping.QUERY_CUSTOMER_CASH)
    @ResponseBody
    public com.sxbbc.common.basics.rest.RestResponse queryCustomerCash(DataCashVO vo) {
        if (vo.getSearchNum() == null) {
            vo.setSearchNum(10);
        }
        if (vo.getTimeDays() == null) {
            vo.setTimeDays(30);
        }
        List<DataCashVO> list = sysCashDetailsMapper.queryCustomerCash(vo);
        if (list != null && list.size() > 0) {
            for (DataCashVO cashVO : list) {
                if (cashVO.getParentid() != null) {
                    CCustomer customer = customerService.getById(cashVO.getParentid());
                    if (customer != null) {
                        cashVO.setParentName(customer.getNickName());
                    }
                }
            }
        }
        return RestFactory.success(list, vo.getSearchNum());
    }


    /**
     * 商家交易账户提现排行-页面
     *
     * @return
     */
    @RequestMapping(value = AccountMapping.SHOW_BUSINESS_CASH)
    public ModelAndView showBusinessCash(DataCashVO vo) {
        ModelAndView view = new ModelAndView(AccountMapping.SHOW_BUSINESS_CASH);
        view.addObject("vo", vo);
        return view;
    }


    /**
     * 查询商家提现排行列表
     *
     * @param vo 查询条件
     * @return
     */
    @RequestMapping(value = AccountMapping.QUERY_BUSINESS_CASH)
    @ResponseBody
    public com.sxbbc.common.basics.rest.RestResponse queryBusinessCash(DataCashVO vo) {
        if (vo.getSearchNum() == null) {
            vo.setSearchNum(10);
        }
        if (vo.getTimeDays() == null) {
            vo.setTimeDays(30);
        }
        List<DataCashVO> list = sysCashDetailsMapper.queryBusinessCash(vo);
        return RestFactory.success(list, vo.getSearchNum());
    }


    /**
     * 商家交易排行页面
     *
     * @return
     */
    @RequestMapping(value = AccountMapping.SHOW_BUSINESS_TRANSACTION)
    public ModelAndView showBusinessTransaction(DataTransactionVo vo) {
        ModelAndView view = new ModelAndView(AccountMapping.SHOW_BUSINESS_TRANSACTION);
        view.addObject("vo", vo);
        return view;
    }

    /**
     * 查询商家交易排行列表
     *
     * @param vo 查询条件
     * @return
     */
    @RequestMapping(value = AccountMapping.QUERY_BUSINESS_TRANSACTION)
    @ResponseBody
    public com.sxbbc.common.basics.rest.RestResponse queryBusinessTransaction(DataTransactionVo vo) {
        if (vo.getSearchNum() == null) {
            vo.setSearchNum(10);
        }
        if (vo.getTimeDays() == null) {
            vo.setTimeDays(30);
        }
        List<DataTransactionVo> list = bAccountService.queryBusinessTransaction(vo);
        return RestFactory.success(list, vo.getSearchNum());
    }


    /**
     * 商家账户明细页面
     *
     * @return
     * @author Wahyee
     */
    @RequestMapping(value = AccountMapping.SHOW_BUSINESS_ACCOUNT)
    public ModelAndView showBusinessAccount() {
        ModelAndView view = new ModelAndView(AccountMapping.SHOW_BUSINESS_ACCOUNT);
        return view;
    }

    /**
     * 查询商家账户列表
     *
     * @param page 分页条件
     * @param vo   查询条件
     * @return
     * @author Wahyee
     */
    @RequestMapping(value = AccountMapping.QUERY_BUSINESS_ACCOUNT)
    @ResponseBody
    public com.sxbbc.common.basics.rest.RestResponse queryBusinessAccount(BasePage<BAccountVO> page, BAccountVO vo) {
        bAccountService.queryPage(page, vo);
        return RestFactory.success(page.getRecords(), page.getTotal());
    }

    /**
     * 商家资金账户明细页面
     *
     * @return
     * @author Wahyee
     */
    @RequestMapping(value = AccountMapping.SHOW_BUSINESS_ACCOUNT_DETAIL)
    public ModelAndView showBusinessAccountDetail(Integer bid) {
        ModelAndView view = new ModelAndView(AccountMapping.SHOW_BUSINESS_ACCOUNT_DETAIL);
        view.addObject("bid", bid);
        return view;
    }

    /**
     * 查询商家资金明细列表
     *
     * @param vo 资金明细查询条件
     * @return
     * @author Wahyee
     */
    @RequestMapping(value = AccountMapping.QUERY_BUSINESS_ACCOUNT_DETAIL)
    @ResponseBody
    public com.sxbbc.common.basics.rest.RestResponse queryBusinessAccountDetail(BasePage<T> page, AccountDetailVO vo) {
        String timestr = vo.getTimestr();
        if (null == vo.getBid()) {
            return RestFactory.fail("商家信息获取失败，请刷新后重试");
        }
        if (vo.getFundType() == null) {
            vo.setFundType(FundTypeEnums.MONEY.getId());
        }
        if (StringUtils.isBlank(vo.getPayCode())) {
            vo.setPayCode(null);
        }

        CalcuUtils calc = CalcuUtils.getInstance();
        if (calc.isEquals(vo.getFundType(), FundTypeEnums.MONEY.getId())) {
            BMoneyDetail entiy = new BMoneyDetail();
            BeanUtils.copyProperties(vo, entiy);
            QueryWrapper<BMoneyDetail> wrapper = new QueryWrapper<BMoneyDetail>(entiy);

            wrapper.orderByDesc("id");
            if (!StringUtils.isBlank(timestr)) {
                String[] timeArr = timestr.split("~");
                if (!StringUtils.isBlank(timeArr[0]) && !StringUtils.isBlank(timeArr[1])) {
                    wrapper.between("create_time", timeArr[0], timeArr[1]);
                }
            }

            Page<BMoneyDetail> page1 = new BasePage<BMoneyDetail>();
            page1.setCurrent(page.getCurrent());
            bMoneyDetailService.page(page1, wrapper);
            for (BMoneyDetail o : page1.getRecords()) {
                o.setTypeName(HandleTypeEnums.getName(o.getTypeId()));
            }
            return RestFactory.success(page1.getRecords(), page1.getTotal());
        }
        return RestFactory.success(page.getRecords(), page.getTotal());
    }

    /**
     * 页面 平台数据列表
     *
     * @return org.springframework.web.servlet.ModelAndView
     * @author leehao
     */
    @RequestMapping(value = AccountMapping.SHOW_PLAT_DEAL_DATA)
    public ModelAndView showPlatDealData() {
        ModelAndView view = new ModelAndView(AccountMapping.SHOW_PLAT_DEAL_DATA);
        return view;
    }

    /**
     * 数据接口 平台数据列表
     *
     * @return com.sxbbc.common.basics.rest.RestResponse
     * @author leehao
     */
    @RequestMapping(value = AccountMapping.QUERY_PLAT_DEAL_DATA)
    @ResponseBody
    public RestResponse showDealData(BasePage<SysDealData> page) {
        QueryWrapper<SysDealData> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");
        sysDealDataService.page(page, wrapper);
        return RestFactory.success(page.getRecords(), page.getTotal());
    }

    /**
     * 页面 编辑平台平台数据
     *
     * @param id
     * @return org.springframework.web.servlet.ModelAndView
     * @author leehao
     */
    @RequestMapping(value = AccountMapping.SHOW_EDIT_DEAL_DATA)
    public ModelAndView showEditDealData(Integer id) {
        SysDealData dealData = sysDealDataService.getById(id);
        ModelAndView view = new ModelAndView(AccountMapping.SHOW_EDIT_DEAL_DATA);
        view.addObject("dealData", dealData);
        return view;
    }

    /**
     * 保存编辑数据
     *
     * @param dealData
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @RequestMapping(value = AccountMapping.EDIT_DEAL_DATA)
    @ResponseBody
    public com.function.common.RestResponse editDealData(SysDealData dealData) {
        if (dealData.getId() == null) {
            return GetRest.getFail("获取数据失败");
        }
        SysDealData sysDealData = sysDealDataService.getById(dealData.getId());
        if (sysDealData == null) {
            return GetRest.getFail("该记录不存在");
        }
        if (dealData.getUnitReal() == null) {
            return GetRest.getFail("请输入比例");
        }
        //得到当日计算后的总共享值(总共享值=单元共享值*比例)
        BigDecimal totalShare = sysDealData.getUnitCal().multiply(dealData.getUnitReal());
        //设置输入的比例
        sysDealData.setUnitReal(dealData.getUnitReal());
        //设置总共享值
        sysDealData.setUnitTotal(totalShare);
        //保存当日发放的总共享值
        sysDealData.setSendTotalShare(totalShare);
        boolean save = sysDealDataService.updateById(sysDealData);
        if (!save) {
            throw new ThrowJsonException("保存数据失败");
        }
        return GetRest.getSuccess("保存成功");
    }

//    /**
//     * 发放记录
//     *
//     * @param id 记录的ID
//     * @return com.function.common.RestResponse
//     * @author leehao
//     */
//    @RequestMapping(value = AccountMapping.HANDLE_SEND_DEAL_DATA)
//    @ResponseBody
//    public com.function.common.RestResponse sendSysDealData(Integer id) {
//        SysDealData sysDealData = sysDealDataService.getById(id);
//        if (sysDealData == null) {
//            return GetRest.getFail("该条数据不存在");
//        }
//        if (CalcuUtils.getInstance().isEquals(sysDealData.getStatus(), StaticUtils.STATUS_YES)) {
//            return GetRest.getFail("该记录已发放，请勿重复操作");
//        }
//        if (sysDealData.getUnitReal() == null) {
//            return GetRest.getFail("获取比例失败");
//        }
////		String  r = modeService.handleSendPlatData(sysDealData);
//        DateUtil dateUtil = DateUtil.getInstance();
//        CalcuUtils calUtil = CalcuUtils.getInstance();
//        /* 0. 获取系统参数——转换单元比例 */
//        BigDecimal donateToUnit = calUtil.getValueByClass(BigDecimal.class, infoParamService.getValueByCode(ParamEnums.DONATE_TO_UNIT));
//        /* 1.分红数据 */
//        BigDecimal unitReal = sysDealData.getUnitReal();
//        /* 2.分红明细表 */
//        //2.1 用户分红明细
//        List<SysDealDetail> dealDetailList = sysDealDetailMapper.queryDetailListByDate(sysDealData.getCreateTime(),
//                StaticUtils.CUSTOMER_ACCOUNT_SUM);
//        long start = System.currentTimeMillis() / 1000;
//        if (!CollectionUtils.isEmpty(dealDetailList)) {
////			List<List<SysDealDetail>> r = FunctionUtils.listGroup(dealDetailList, 1000);
////			for(List<SysDealDetail> sdd: r) {
////				System.out.println(sdd.size());
////			}
////			int i = 0;
//            for (SysDealDetail d : dealDetailList) {
////				if(i >= 5000) {
////					break;
////				}
////				i++;
//                try {
//                    modeService.handleSendPlatData(d, unitReal, donateToUnit, sysDealData.getServiceCode());
//                } catch (ThrowJsonException ex) {
//                    return GetRest.getFail(ex.getMessage());
//                } catch (Exception e) {
//                    return GetRest.getFail("处理发放平台数据失败");
//                }
//            }
//        } else {
//            sysDealData.setRemark("当日用户无明细记录,该条记录处理为发放");
//        }
//        long end = System.currentTimeMillis() / 1000;
//        System.out.println("共运行时间（秒）:" + (end - start));
//        //2.2代理分红
//        List<SysDealDetail> agentDealDetail = sysDealDetailMapper.queryDetailListByDate(sysDealData.getCreateTime(),
//                StaticUtils.AGENT_ACCOUNT_SUM);
//        if (!CollectionUtils.isEmpty(agentDealDetail)) {
//            for (SysDealDetail d : agentDealDetail) {
//                try {
//                    modeService.handleSendPlatData(d, unitReal, donateToUnit, sysDealData.getServiceCode());
//                } catch (ThrowJsonException ex) {
//                    return GetRest.getFail(ex.getMessage());
//                } catch (Exception e) {
//                    return GetRest.getFail("处理发放平台数据失败");
//                }
//            }
//        } else {
//            sysDealData.setRemark("当日代理无明细记录,该条记录处理为发放");
//        }
//
//        //更新平台数据表
//        //发放时计算系统总共享值（系统总共享值=今日计算共享值+昨日总共享值）
//        //拿到上一日的记录
//        BigDecimal yesterdayUnitTotal = sysDealDataService.getYesterdayUnitTotal(sysDealData.getCreateTime());
//        //显示的总共享值=昨日的记录+今日的总共享值
//        BigDecimal showUnitTotal = BigDecimal.ZERO;
//        if (yesterdayUnitTotal != null) {
//            showUnitTotal = calUtil.add(yesterdayUnitTotal, sysDealData.getUnitTotal(), 2);
//        } else {
//            showUnitTotal = sysDealData.getUnitTotal();
//        }
//        sysDealData.setUnitTotal(showUnitTotal);
//        //状态设置为1 客户端才可拿到此数据
//        sysDealData.setStatus(StaticUtils.STATUS_YES);
//        boolean save = sysDealDataService.updateById(sysDealData);
//        if (!save) {
//            return GetRest.getFail("变更分红数据状态失败");
//        }
//        return GetRest.getSuccess("发放成功");
////		if(r.length() > 0) {
////			return GetRest.getFail(r);
////		}
////		return GetRest.getSuccess("发放成功");
//    }

}
